package com.probox.common.entity.utils;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.entity.vo.im.Token;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;


/**
 * 连接池
 */
public class ConnectionPool {


    private static final Logger logger = LoggerFactory.getLogger(ConnectionPool.class);

    public static final AttributeKey<Token> USER_INFO = AttributeKey.valueOf("user_token");
    private static final ConnectionPool INSTANCE = new ConnectionPool();
    private ConcurrentHashMap<String,Channel> channels;
    private ConnectionPool() {
        channels=new ConcurrentHashMap<>();
    }
    public static ConnectionPool getInstance() {
        return INSTANCE;
    }
    /**
     * 用户登录成功之后才会放入链接池
     */
    public boolean add(final Token token,Channel channel) {
        if ( null == token || channel == null ) {
            logger.info("token 为空，不能添加!");
            return false;
        }
        String key= CachePrefix.CUSTOMER_CHAT+"CHANNEL"+token.getRole()+token.getUid();
        if (!channels.containsKey(key)) {
        	channel.attr(USER_INFO).set(token);
        	channels.put(key,channel);
        }else {
        	Channel old = channels.get(key);
        	if (!old.isActive()) {
        		channel.attr(USER_INFO).set(token);
        		channels.put(key,channel);
        	}
        }
        return true;
    }


    /**
     *	删除token对应的channel
     * @param token
     */
    public void remove(final Token token){
        if (token != null) {
            String key = CachePrefix.CUSTOMER_CHAT + "CHANNEL" + token.getRole() + token.getUid();
            channels.remove(key);
        }
    }

    public void remove(Channel channel){
        Attribute<Token> ak = channel.attr(USER_INFO);
        if (ak != null) {
            remove(channel.attr(USER_INFO).get());
        }
    }

    /**
     * 获取通道
     * @param token
     * @return
     */
    public Channel getChannel(final Token token) {
        String key=CachePrefix.CUSTOMER_CHAT+"CHANNEL"+token.getRole()+token.getUid();
        return channels.get(key);
    }


}
